import axios from 'axios'
import token from '@/utils/token'
import config from '@/config'

const mimeMap = {
    xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    zip: 'application/zip'
}

const baseUrl = config.apiContextPath

export function downLoadZip(url, filename) {
    url = baseUrl + url
    axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: {[token.getKey()]: token.get()}
    }).then(res => {
        resolveBlobZip(res, mimeMap.zip)
    })
}

export function downLoadExcel(url, filename) {
    url = baseUrl + url
    return new Promise((resolve, reject) => {
        axios({
            method: 'get',
            url: url,
            responseType: 'blob',
            headers: {[token.getKey()]: token.get()}
        }).then(res => {
            resolveBlob(resolve, res, mimeMap.xlsx, filename)
        })
    })
}
/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlobZip(res, mimeType) {
    const aLink = document.createElement('a')
    var blob = new Blob([res.data], {type: mimeType})
    //  // 从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
    var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
    var contentDisposition = decodeURI(res.headers['content-disposition'])
    var result = patt.exec(contentDisposition)
    var fileName = result[1]
    fileName = fileName.replace(/"/g, '')
    aLink.href = URL.createObjectURL(blob)
    aLink.setAttribute('download', fileName) //  设置下载文件名称
    document.body.appendChild(aLink)
    aLink.click()
    document.body.appendChild(aLink)
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlob(resolve, res, mimeType, fileName) {
    const aLink = document.createElement('a')
    var blob = new Blob([res.data], {type: mimeType})
    //  // 从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
    var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
    var contentDisposition = decodeURI(res.headers['content-disposition'])
    var result = patt.exec(contentDisposition)
    if (!fileName) {
        fileName = result[0]
        fileName = fileName.replace(/"/g, '')
    }
    aLink.href = URL.createObjectURL(blob)
    aLink.setAttribute('download', fileName) //  设置下载文件名称
    document.body.appendChild(aLink)
    aLink.click()
    document.body.appendChild(aLink)
    if (resolve) {
        return resolve(200)
    }
}
